var prefix = "/order/manage";
$(function () {
    $("#province").val("");
    $("#city").val("");

    layui.use('laydate', function(){
        var laydate = layui.laydate;
        laydate.render({
            elem: '#start'
            ,type: 'datetime'
        });

        laydate.render({
            elem: '#end'
            ,type: 'datetime'
        });
    });

    load();
});
$('#orderTable').on('load-success.bs.table', function (e, data) {
    if (data.total && !data.rows.length) {
        $('#orderTable').bootstrapTable('selectPage').bootstrapTable('refresh');
    }
});

function load() {
    $('#orderTable').bootstrapTable(
            {
                method: 'get', // 服务器数据的请求方式 get or post
                url: prefix + "/list", // 服务器数据的加载地址
                showRefresh: true,
                // showToggle : true,
                iconSize: 'outline',
                // toolbar: '#exampleToolbar',
                striped: true, // 设置为true会有隔行变色效果
                dataType: "json", // 服务器返回的数据类型
                pagination: true, // 设置为true会在底部显示分页条
                pageList:[10,20,50],
                // queryParamsType : "limit",
                // //设置为limit则会发送符合RESTFull格式的参数
                singleSelect: false, // 设置为true将禁止多选
                // contentType : "application/x-www-form-urlencoded",
                // //发送到服务器的数据编码类型
                pageSize: 10, // 如果设置了分页，每页数据条数
                pageNumber: 1, // 如果设置了分布，首页页码
                // search : true, // 是否显示搜索框
                showColumns: false, // 是否显示内容下拉框（选择显示的列）
                sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: params.offset,
                        order: 'desc',
                        queryItem: $.trim($("#queryItem").val()),
                        payStatus: $('#payStatus').val(),
                        centreId:$("*[name='centreId']").val(),
                        province:$('#province').val(),
                        city: $('#city').val(),
                        dispatchid: $('#dispatchid').val(),
                        start: $('#start').val(),
                        end:$('#end').val(),
                        spellgroupStu:$('#spellgroupStu').val(),
                        orderType: 2
                    };
                },
                columns: [
                    {
                        field: 'id',
                        title: '订单ID'
                    },
                    {
                        field:'centreName',
                        title: '商户',
                        visible: show_centre
                    },
                    {
                        field: 'goodstotal',
                        title: '商品信息',
                        width: '40%',
                        formatter: function (value, row, index) {
                            return formatProductInfo(row.orderProducts, row.ordersn);
                        }
                    },
                    {
                        field: 'mid',
                        title: '买家信息',
                        formatter: function (value, row, index) {
                            var dispatchtype = '门店家自提';
                            var iscomment = "无";
                            if(row.iscomment!=""){
                            	iscomment = row.iscomment;
                            }
                            if(row.iscomment==0){
                            	iscomment = "无";
                            }
                            if (row.dispatchtype != 0) {
                                dispatchtype = '直邮';
                            }
                            if (row.dispatchid != 0) {
                                dispatchtype = '快递直发';
                            }
                            var m = '<p>'+ "所属门店:"+ row.tXiaoqu+"  门店Id:"+row.tMid+ '<span class="label label-primary">'+dispatchtype+'</span></p>';
                            var d = '<p>'+ "自提地址:"+ row.address+'</p>';
                            var s = '<p>'+ "下单人:"+ row.nickname+'</p>';
                            var r = '<p>'+ "收货人:"+ row.sname+'</p>';
                            var p = '<p>'+ "手机号:"+ row.mobile+'</p>';
                            var c = '<p style="color: red;">'+ "备注:"+iscomment+'</p>';
                            return m + d + s + r + p+c;
                        }
                    },
                    {
                        field: 'goodsprice',
                        title: '费用',
                        formatter: function (value, row, index) {
                            var  py='';
                            if (row.paystatus == 0) {
                                py =  '<label class="label label-default">未支付</label>';
                            }else if (row.paystatus == 1) {
                                var payType = row.paytype;
                                if (payType === 1) {
                                    py = '<label class="label label-danger">余额支付</label>';
                                }else if (payType === 2) {
                                    py = '<label class="label label-success">微信支付</label>';
                                }else {
                                    py = '<label class="label label-info">微信+余额</label>';
                                }
                            }else if (row.paystatus == -1){
                                py =  '<label class="label label-default">已取消</label>';
                            }

                            var p = '<p style="margin-top: 20px">'+ "商品小计:"+ value+'</p>';
                            var d = '<p>'+ "运费:"+ row.dispatchprice+'</p>';
                            var y = '<p>'+ "优惠卷抵扣:"+ row.discountprice+'</p>';
                            var j = '<p>'+ "积分抵扣:"+ row.deductprice+'</p>';
                            var pp = '<p style="color: green">'+ "应付:"+ row.payprice+'</p>';
                            return py + p + d +y+j+ pp;
                        }
                    },
                    {
                        field: 'createTime',
                        title: '时间',
                        formatter: function (value, row, index) {
                            var c = '<p>下单时间:'+ value+'</p>';
                            var p = '<p>支付时间:'+ row.payTime+'</p>';
                            return c+p;
                        }
                    },
                    {
                        field: 'status',
                        title: '状态',
                        formatter: function (value, row, index) {
                            if (value == -1) {
                                return '<label class="label label-default">已关闭</label>'
                            }else if (value == 0) {
                                return '<label class="label label-danger">待付款</label>'
                            }else if (value == 1) {
                                return '<label class="label label-info">待发货</label>'
                            }else if (value == 2) {
                                return '<label class="label label-warning">待收货</label>'
                            }else if (value == 3) {
                                return '<label class="label label-success">已收货</label>'
                            }else if (value == 4) {
                                return '<label class="label label-yellow">待退款</label>'
                            }else if(value == 5) {
                                return '<label class="label label-yellow">售后中</label>'
                            } else {
                               return '<label class="label label-success">已完成</label>'
                            }
                        }
                    },
                    {
                        title: '操作',
                        field: 'id',
                        align: 'center',
                        formatter: function (value, row, index) {
                            var detail = '<a class="btn btn-success btn-xs ' + s_detail_h + '" href="#" mce_href="#" title="详情" onclick="detail(\''
                                + value + '\')">' + '<i class="fa fa-eye"></i>查看详细</a>';

                            var close = '<a class="btn btn-default btn-xs ' + s_close_h + '" href="#" mce_href="#" title="关闭" onclick="closeOrder(\''
                                + value + '\')">' + '<i class="fa fa-remove"></i>关闭订单</a>';

                            var  refund = '<a class="btn btn-danger btn-xs ' + s_refund_h + '" href="#" mce_href="#" title="退款" onclick="refundOrder(\''
                                + value + '\')">' + '<i class="fa fa-recycle"></i>申请退款</a>';

                            var  send = '<a class="btn btn-primary btn-xs ' + s_send_goods_h + '" href="#" mce_href="#" title="发货" onclick="sendGoods(\''
                                + value + '\')">' + '<i class="fa fa-check-circle"></i>确认发货</a>';

                            var received = '<a class="btn btn-info btn-xs ' + s_confirm_received_h + '" href="#" mce_href="#" title="收货" onclick="received(\''
                                + value + '\')">' + '<i class="fa fa-chrome"></i>确认收货</a>';


                            if (row.status == 0 || row.status == 3) {
                                /**待付款**/
                                return detail +'<br>'+ close;
                            }else if (row.status == 1 && row.dispatchid == 0) {
                                return detail +'<br>'+ refund +'<br>'+ send;
                            }else if (row.status == 2 && row.dispatchid == 0 ) {
                                return detail + '<br>' + received;
                            }else if (row.status == 4 || row.status == -1) {
                                return detail;
                            }else {
                                return detail;
                            }
                        }
                    }]
            });
}
function reLoad() {
    $('#orderTable').bootstrapTable('refresh');
}

/**
 * 格式化商品列信息
 * @param orderProducts 订单商品列表
 * @param orderSn 订单编号
 */
function formatProductInfo(orderProducts,orderSn) {
    var info = "<span class='label label-light'>订单编号:"+ orderSn+"</span>";
    if (orderProducts && orderProducts.length >0) {
        for (var i=0; i<orderProducts.length; i++) {
            var item = orderProducts[i];
            var product_status = '';
            var  refund ='';
            var l = "";
            if(item.isLiansuo==1){
            	l='<span style="color: red;">是该门店门店商品</span>';
            }
            if (item.status === -1) {
                product_status =  '<span class="label label-warning">已取消</span>';
                if (item.payStatus === 0) {
                    refund = '<span class="label label-info">未支付</span>';
                } else if (item.payStatus === -1) {
                    refund = '<span class="label label-danger">已退款</span>';
                }
            }else if (item.status === 1) {
                product_status =  '<span class="label label-danger">待发货</span>';
                if (orderProducts.length > 1) {
                    refund = '<a shiro:haspermission="order:manage:refund" title="退款"><button class="btn btn-xs btn-danger" onclick="refundSingle(\''+item.id+ '\')">单品退款</button></a>'
                }
            }else if (item.status === 2) {
                product_status = '<span class="label label-success">已发货</span>';
                if (orderProducts.length > 1) {
                    refund = '<a shiro:haspermission="order:manage:refund" title="退款"><button class="btn btn-xs btn-danger" onclick="refundSingle(\''+item.id+ '\')">单品退款</button></a>'
                }
            }else if (item.status === 3) {
                product_status = '<span class="label label-primary">已收货</span>';
            }else if (item.status === 4) {
                refund = '<span class="label label-danger">退款中</span>';
            }else if (item.status === 5) {
                refund = '<span class="label label-danger">售后中</span>';
            }else if (item.status === 6) {
                product_status = '<span class="label label-primary">已完成</span>';
            } else {
                 product_status = '';
                 refund ='';
            }
            if(item.isKuaidi==1){
            	var sn = "暂无";
            	if(item.kuaidisn != ""){
            		sn = item.kuaidisn;
            	}
            	
            	
            	info = info
                +'<table class="table">'
                +'<tbody>'
                +'<tr>'
                    +'<td style="width: 50px"><img src='+ item.thumb+' style="width:50px;height:50px"></td>'
                    +'<td style="border: 0px">'+ item.productName+ '<br>'
                            + product_status
                    +'</td>'
                    +'<td style="text-align:right;border: 0px">' +
                '         '+l+'<br>'
                           +'原价:'+item.productprice +'<br>'
                           +'应付:'+item.marketprice +'<br>'
                           +'数量:'+item.total +'<br>'
                           +'快递单号:'+sn+'<br>'
                           +'收货地址:'+item.province+item.city +item.district+item.address+'<br>'
                           + refund
                    + '</td>'
                + '</tr>'
                + '</tbody>'
                +'</table>'
            	
            }else{
	            info = info
	                +'<table class="table">'
	                +'<tbody>'
	                +'<tr>'
	                    +'<td style="width: 50px"><img src='+ item.thumb+' style="width:50px;height:50px"></td>'
	                    +'<td style="border: 0px">'+ item.productName+ '<br>'
	                            + product_status
	                    +'</td>'
	                    +'<td style="text-align:right;border: 0px">' +
	                '         '+l+'<br>'
	                           +'原价:'+item.productprice +'<br>'
	                           +'应付:'+item.marketprice +'<br>'
	                           +'数量:'+item.total +'<br>'
	                           + refund
	                    + '</td>'
	                + '</tr>'
	                + '</tbody>'
	                +'</table>'
            }
        }
    }
    return info;
}

/**
 * 订单详情页面
 * @param orderId
 */
function detail(orderId) {
    layer.open({
        id:'order_detail',
        type : 2,
        title : '订单详情',
        maxmin : true,
        shadeClose : false,
        area : [ '60%', '80%' ],
        content : prefix + '/detail/' + orderId // iframe的url
    });
}


/**
 * 单品退款
 * @param orderProductId
 */
function refundSingle(orderProductId) {
    layer.confirm('确定要申请退款吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/refundSingle",
            type: "POST",
            data: {
                'orderProductId': orderProductId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}
/**
 * 关闭订单
 * @param orderId
 */
function closeOrder(orderId) {
    layer.confirm('确定要关闭该订单吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/closeOrder",
            type: "POST",
            data: {
                'orderId': orderId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

/**
 * 退款申请
 * @param orderId
 */
function refundOrder(orderId) {
    layer.confirm('确定要后台申请退款吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/refundOrder",
            type: "POST",
            data: {
                'orderId': orderId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

/**
 * 退款申请
 * @param orderId
 */
function sendGoods(orderId) {
    layer.confirm('您确定要发货吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/sendGoods",
            type: "POST",
            data: {
                'orderId': orderId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}


/**
 * 退款申请
 * @param orderId
 */
function received(orderId) {
    layer.confirm('您确定要收货吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/confirmReceived",
            type: "POST",
            data: {
                'orderId': orderId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

/**
 * 待收货记录导出
 */
function exportOrders() {
    var queryItem = $.trim($("#queryItem").val());
    var payStatus = $('#payStatus').val();
    var centreId = $("*[name='centreId']").val();
    var province = $('#province').val();
    var city = $('#city').val();
    var start = $('#start').val();
    var end = $('#end').val();
    var dispatchid = $('#dispatchid').val();
    window.location.href = prefix + "/export?centreId=" + centreId + "&queryItem=" + queryItem + "&start=" + start + "&end=" + end +
        "&payStatus=" + payStatus + "&province="+ province+ "&city="+ city+"&dispatchid="+dispatchid;
}